package put.cs.two.to.tsp.io;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import put.cs.two.to.tsp.models.NodeSet;
import put.cs.two.to.tsp.models.Point;

public class NodeSetFileReader {

    private static final String LAST_HEADER_VALUE = "NODE_COORD_SECTION";

    private static final String EOF = "EOF";

    private String inputFilename;

    public NodeSetFileReader(String inputFilename) {
        this.inputFilename = inputFilename;
    }

    public NodeSet readNodeSet() {
        NodeSet result = new NodeSet();
        try {
            BufferedReader in = new BufferedReader(new FileReader(inputFilename));
            skipHeader(in);

            String line;
            while ((line = in.readLine()) != null) {
                if (!line.equals(EOF)) {
                    String[] words = line.split(" ");
                    int index = Integer.parseInt(words[0]);
                    int x = Integer.parseInt(words[1]);
                    int y = Integer.parseInt(words[2]);
                    Point point = new Point(x, y);
                    point.setIndex(index);
                    result.add(point);
                }
            }
            in.close();
        } catch (IOException e) {
            System.err.println("Error while parsing input file");
            e.printStackTrace();
            return null;
        }
        return result;
    }

    private void skipHeader(BufferedReader in) throws IOException {
        String line;
        while ((line = in.readLine()) != null) {
            if (line.equals(LAST_HEADER_VALUE)) {
                break;
            }
        }
    }
}
